package com.javasm.service.impl;

import com.javasm.domain.LoginUser;
import com.javasm.domain.ResponseResult;
import com.javasm.domain.User;
import com.javasm.service.LoginService;
import com.javasm.utlis.JwtUtil;
import com.javasm.utlis.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author：MoDebing
 * @Version：1.0
 * @Date：2022-09-01-18:06
 * @Description: 登录功能实现业务逻辑
 */
@Service
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;
    private final RedisCache redisCache;

    public LoginServiceImpl(AuthenticationManager authenticationManager, RedisCache redisCache) {
        this.authenticationManager = authenticationManager;
        this.redisCache = redisCache;
    }

    @Override
    public ResponseResult login(User user) {

        // 要把登录的用户名和密码封装成Authentication对象然后传入authenticationManager才能进行认证
        //UsernamePasswordAuthenticationToken是Authentication的具体实现
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());


        //AuthenticationManager authenticationManager进行用户认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证没通过，给出相应的提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登陆失败");
        }

        // 如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(userId.toString());
        HashMap<String,String> userInfoTokenMap = new HashMap<>(1);
        userInfoTokenMap.put("token",jwt);
        // 把完整的用户信息存入redis userid作为key
        redisCache.setCacheObject("login:"+userId,loginUser,5, TimeUnit.MINUTES);
        return new ResponseResult(200,"登陆成功",userInfoTokenMap);
    }

    // 退出登录
    @Override
    public ResponseResult logout() {
        // 获取securityContextHolder中 的id(不需要删除securityContextHolder的值，
        // 因为请求过来的时候首先会先经过我们自定义的过滤器，然后去redis找相应的用户信息，
        // 如果不存在就直接提示用户未登录了，所以不需要处理)
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        // 删除redis中的值
        redisCache.deleteObject("login:"+userId);

        return new ResponseResult(200,"注销成功！");
    }
}
